package dao

import (
	"gitee.com/mangenotwork/game-douniu/api/common"
	"gitee.com/mangenotwork/game-douniu/api/entity"
	"math/rand"
	"time"
)

type RoomDao struct {
}

func (dao *RoomDao) NewRoom(userId int64) (*entity.Room, error) {
	db := common.GetGorm("test")

	roomId := dao.GetRoomId()

	data := &entity.Room{
		RoomId:    roomId,
		UserId:    userId,
		State:     1,
		CreatedAt: time.Now().Unix(),
	}

	err := dao.SetRoomId(roomId)
	if err != nil {
		return nil, err
	}
	err = db.Model(&entity.Room{}).Create(data).Error
	return data, err
}

func (dao *RoomDao) DissolutionRoom(roomId int64) error {
	db := common.GetGorm("test")
	ex := map[string]any{"state": 2}
	return db.Model(&entity.Room{}).Where("room_id=?", roomId).Updates(ex).Error
}

func (dao *RoomDao) GetRoomId() int64 {
	roomIdData := &entity.RoomId{}
	db := common.GetGorm("test")
	err := db.Model(&entity.RoomId{}).First(&roomIdData).Error
	if err != nil {
		return 0
	}

	rand.Seed(time.Now().UnixNano())
	num := rand.Intn(10) + 10

	return roomIdData.Value + int64(num)
}

func (dao *RoomDao) SetRoomId(roomId int64) error {
	db := common.GetGorm("test")
	return db.Model(&entity.RoomId{}).Where("id=1").Update("value", roomId).Error
}
